#ifndef WIN_SERIAL_H
#define WIN_SERIAL_H
#include <windows.h>
#include <QThread>
#include "qserialbase.h"

class QReadWriteLock;
class Win_SerialThread;

class Win_Serial :public QSerialBase
{
    Q_OBJECT
    friend class Win_QextSerialThread;
public:

    Win_Serial();
    Win_Serial(int iPort,
               const PortSettings& settings,
               QSerialBase::QueryMode mode = QSerialBase::EventDriven);

    virtual ~Win_Serial();



    void monitorCommEvent();
    void terminateCommWait();
//protected:
    virtual qint64 readData(char *data, qint64 maxSize);
    virtual qint64 writeData(const char *data, qint64 maxSize);
public:
    virtual bool open(OpenMode mode);
    virtual void close();
    virtual void flush();

    virtual void setFlowControl(FlowType);
    virtual void setParity(ParityType);
    virtual void setDataBits(DataBitsType);
    virtual void setStopBits(StopBitsType);
    virtual void setBaudRate(BaudRateType);
    virtual void setDtr(bool set=true);
    virtual void setRts(bool set=true);
    virtual void setTimeout(long);

    virtual qint64 bytesAvailable();
    virtual ulong lineStatus(void);
    virtual qint64 size() const;
    virtual void translateError(ulong);


    virtual qint64 bytesToWrite() const;
protected:
    void init();
protected:
    HANDLE Win_Handle;
    HANDLE threadStartEvent;
    HANDLE threadTerminateEvent;
    OVERLAPPED overlap;
    OVERLAPPED overlapWrite;
    COMMCONFIG Win_CommConfig;
    COMMTIMEOUTS Win_CommTimeouts;
    QReadWriteLock * bytesToWriteLock;	///< @todo maybe move to QextSerialBase.
    qint64 _bytesToWrite;		///< @todo maybe move to QextSerialBase (and implement in POSIX).
    Win_SerialThread * overlapThread; ///< @todo maybe move to QextSerialBase (and implement in POSIX).


};

class Win_SerialThread: public QThread
{
protected:
    Win_Serial * qesp;
    bool terminate;

    public:

        Win_SerialThread(Win_Serial * qesp);
        void stop();

    protected:
        virtual void run();

};

#endif // WIN_SERIAL_H
